import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { NzUploadFile } from 'ng-zorro-antd/upload';
import { Brand } from 'src/app/model/brand';
import { environment } from '../../../../../environments/environment';
import { FileApiService } from 'src/app/api/file-api.service';
import { BrandApiService } from 'src/app/api/brand-api.service';
import { NzMessageService } from 'ng-zorro-antd/message'
import { FileExtraData } from 'src/app/model/fileExtraData';
import { FileUploder } from 'src/app/utils/file-uploder';




@Component({
  selector: 'app-brand-detial',
  templateUrl: './brand-detial.component.html',
  styleUrls: ['./brand-detial.component.less', '../../../../styles/container.css']
})
export class BrandDetialComponent implements OnInit, OnChanges {

  brandForm: FormGroup;
  fileUploadURL = environment.fileUploadURL;
  @Input() brand: Brand;
  bigPicFileUploader: FileUploder;
  logoFileUploader: FileUploder;

  constructor(
    private fb: FormBuilder,
    private fileApi: FileApiService,
    private brandApi: BrandApiService,
    private message: NzMessageService,
  ) {
    this.bigPicFileUploader = new FileUploder(this.fileApi, this.message);
    this.logoFileUploader = new FileUploder(this.fileApi, this.message);
    this.brandForm = this.fb.group({
      bigPic: [null],
      brandStory: [null],
      factoryStatus: [0],
      firstLetter: [null],
      logo: [null, [Validators.required]],
      name: [null, [Validators.required]],
      showStatus: [0],
      sort: [0, [Validators.pattern('[0-9]*')]],
    })


  }

  ngOnInit(): void { }

  get logo() { return this.brandForm.get('logo'); }
  get name() { return this.brandForm.get('name'); }

  ngOnChanges(changes: SimpleChanges) {
    const curBrandValue = changes['brand'].currentValue;
    this.setFormValue(curBrandValue);
    this.bigPicFileUploader.init([curBrandValue.bigPic]);
    this.logoFileUploader.init([curBrandValue.logo]);
  }

  submitForm() {
    for (const key in this.brandForm.controls) {
      this.brandForm.controls[key].markAsDirty();
      this.brandForm.controls[key].updateValueAndValidity();
    }
    if (this.brandForm.valid) {
      if (this.brand?.id) {
        this.brandApi.update(this.brand.id, this.brandForm.value).subscribe(
          item => {
            this.message.success("品牌编辑成功");
          },
          err => {
            this.message.error("错误");
          }
        );
      } else {
        this.brandApi.create(this.brandForm.value).subscribe(
          item => {
            this.message.success("品牌创建成功")
            setTimeout(() => {
              this.resetForm()
            }, 1000);
          },
          err => {
            this.message.error("错误")
          }
        );
      }
    }
  }

  resetForm() {
    this.brandForm.reset();
    this.bigPicFileUploader.fileList = [];
    this.logoFileUploader.fileList = [];
    this.brandForm.get('showStatus').setValue(0);
    this.brandForm.get('factoryStatus').setValue(0);
    this.brandForm.get('sort').setValue(0);
    for (const key in this.brandForm.controls) {
      this.brandForm.controls[key].markAsPristine();
      this.brandForm.controls[key].updateValueAndValidity();
    }
  }

  handleReset() {
    this.bigPicFileUploader.rest();
    this.logoFileUploader.rest();
    this.resetForm();
  }

  getLogoExtraData = (file: NzUploadFile): FileExtraData => {
    return new FileExtraData('brand', this.brandForm.get('name').value, 'logo');
  }

  getBigPigExtraData = (file: NzUploadFile): FileExtraData => {
    return new FileExtraData('brand', this.brandForm.get('name').value, 'bigPig');
  }

  handlelogoFileChange(e) {
    if (e.type == "success") {
      this.brandForm.get('logo').setValue(e.file.response?.data.url);
      !this.brand?.id || this.submitForm();

    }
    if (e.type == "removed") {
      this.brandForm.get('logo').setValue(null);
      !this.brand?.id || this.submitForm();
    }
  }

  handleBigPicFileChange(e) {
    if (e.type == "success") {
      this.brandForm.get('bigPic').setValue(e.file.response?.data.url);
      !this.brand?.id || this.submitForm();
    }
    if (e.type == "removed") {
      this.brandForm.get('bigPic').setValue(null);
      !this.brand?.id || this.submitForm();
    }
  }

  private setFormValue(source: Brand) {
    this.brandForm.setValue({
      'bigPic': source.bigPic,
      'brandStory': source.brandStory,
      'factoryStatus': source.factoryStatus,
      'firstLetter': source.firstLetter,
      'logo': source.logo,
      'name': source.name,
      'showStatus': source.showStatus,
      'sort': source.sort,
    });
  }
}
